package com.zj.osm.view.home.home;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zj.osm.App;
import com.zj.osm.R;
import com.zj.osm.entity.greendao.Project;
import com.zj.osm.model.pojo.EquipModuleType;
import com.zj.osm.model.pojo.EquipType;
import com.zj.osm.model.service.EquipModuleTypeService;
import com.zj.osm.model.service.EquipTypeService;
import com.zj.osm.model.service.impl.EquipModuleTypeServiceImpl;
import com.zj.osm.model.service.impl.EquipTypeServiceImpl;
import com.zj.osm.mvp.MvpActivity;
import com.zj.osm.utils.ExportUtils;
import com.zj.osm.view.map.map.MapActivity;
import com.zj.osm.view.project.addproject.AddProjectActivity;
import com.zj.osm.view.project.projectdetail.ProjectDetailActivity;
import com.zj.utils.data.LiveDataBus;
import com.zj.utils.swipe.SmartSwipe;
import com.zj.utils.swipe.SmartSwipeRefresh;
import com.zj.utils.swipe.SwipeConsumer;
import com.zj.utils.swipe.SwipeConsumerExclusiveGroup;
import com.zj.utils.swipe.consumer.SlidingConsumer;
import com.zj.utils.utils.ShareUtils;
import com.zj.utils.utils.utilcode.TimeUtils;
import com.zj.utils.utils.utilcode.ToastUtils;
import com.zj.utils.view.TitleBar;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static com.zj.osm.utils.Configuration.PROJECT_ID;

/**
 * 项目主活动，不继承BaseActivity
 */
public class HomeActivity extends MvpActivity<HomeActivityView, HomeActivityPresenter> implements EasyPermissions.PermissionCallbacks, HomeActivityView ,GoFramgent{

    public static final int FIRST_PAGE = 1;
    private int page = FIRST_PAGE;
    private RecyclerView homeItemRv;
    private CommonAdapter<Project> projectCommonAdapter;
    private List<Project> projectList = new ArrayList<>();
    private boolean firstEntry = true;
    private int lastPosition = 0;
    private int lastOffset = 0;
    private HomeBootomTabWidget bootomTabWidget;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        requireSomePermission();// 申请权限
        initView();
    }

    @Override
    public HomeActivityPresenter createPresenter() {
        return new HomeActivityPresenter();
    }

    @Override
    public HomeActivityView createView() {
        return this;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 加载地图的流程
     * 安卓6.0以上需要线请求权限
     */
    private void loadData() {
        if (Build.VERSION.SDK_INT >= 23) {
            requireSomePermission();// 申请权限
        } else {
            //加载数据
            initData();
        }
    }

    /**
     * 通过第三方插件easyPermissions来管理权限问题
     */
    private void requireSomePermission() {
        EasyPermissions.requestPermissions(
                this,
                "申请权限",
                0,
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /*
     * 初始化数据
     */
    private void initData() {
        getPresenter().getProjectList(FIRST_PAGE);
        setAdapter();
        firstEntry = false;
        long time = System.currentTimeMillis();
        EquipTypeService equipTypeService = new EquipTypeServiceImpl();
        List<EquipType> equipTypeList = equipTypeService.getEquipTypeList();
        EquipModuleTypeService equipModuleTypeService = new EquipModuleTypeServiceImpl();
        List<EquipModuleType> equipModuleTypeList = equipModuleTypeService.getEquipModuleTypeList();
        Log.e(TAG, "saveMarker: equipTypeList   " + equipTypeList);
        Log.e(TAG, "saveMarker: equipModuleTypeList   " + equipModuleTypeList);
        Log.e(TAG, "saveMarker: 时间" + (System.currentTimeMillis() - time));

        long time2 = System.currentTimeMillis();
        List<EquipType> equipTypeListByComponent2 = equipTypeService.getEquipTypeListByComponent(1);
        Log.e(TAG, "saveMarker: equipTypeList 2 " + equipTypeListByComponent2);
        Log.e(TAG, "saveMarker: 时间" + (System.currentTimeMillis() - time2));
    }

    /*
     * 设置RecycleView Adapter
     */
    private void setAdapter() {
        projectCommonAdapter = new CommonAdapter<Project>(this, R.layout.adapter_home_project, projectList) {
            private RelativeLayout homeAdRlItem;
            //控制只能有一个左滑
            private SwipeConsumerExclusiveGroup exclusiveGroup = new SwipeConsumerExclusiveGroup();

            @SuppressLint("SetTextI18n")
            @Override
            protected void convert(ViewHolder holder, Project project, int position) {
                homeAdRlItem = holder.getView(R.id.homeAdRlItem);
                holder.setText(R.id.homeAdTvTime, TimeUtils.formatTime(Long.parseLong(project.getTime())));
                holder.setText(R.id.homeAdTvType, project.getType() + "   " + project.getVoltage());
                holder.setText(R.id.homeAdTvName, project.getName());

                inflateSwipe(project);

                homeAdRlItem.setOnClickListener(v -> {
                    LiveDataBus.get().getChannel(PROJECT_ID).setValue(project.getId());
                    startIntent(MapActivity.class);
                });
                homeAdRlItem.setOnLongClickListener(v -> {
                    showNormalDialog(project);
                    return false;
                });
            }
            /**
           * 设置右滑菜单
          * @param project
          */
            private void inflateSwipe(Project project) {
                View view = View.inflate(HomeActivity.this, R.layout.adapter_home_project_swipe, null);
                SwipeConsumer consumer = SmartSwipe.wrap(homeAdRlItem)
                        .addConsumer(new SlidingConsumer())
                        .setScrimColor(0x2F000000)
                        .setRightDrawerView(view)
                        .setInterpolator(new AccelerateDecelerateInterpolator())
                        .addToExclusiveGroup(exclusiveGroup);
                if (consumer.isOpened()) {
                    consumer.close();
                }
                Button homeAdBtnDetails = view.findViewById(R.id.homeAdBtnDetails);
                Button homeAdBtnDelete = view.findViewById(R.id.homeAdBtnDelete);
                Button homeAdBtnTag = view.findViewById(R.id.homeAdBtnTag);
                homeAdBtnDetails.setOnClickListener(v -> {
                    consumer.close();
                    Log.e(TAG, "onClick: 侧滑按钮点击0");
                    ToastUtils.showShort("详情");
                    Bundle bundle = new Bundle();
                    bundle.putLong(PROJECT_ID, project.getId());
                    startIntent(ProjectDetailActivity.class, bundle);
                });
                homeAdBtnDelete.setOnClickListener(v -> {
                    consumer.close(true);
                    Log.e(TAG, "onClick: 侧滑按钮点击1");
                    ToastUtils.showShort("删除");
                });
                homeAdBtnTag.setOnClickListener(v -> {
                    consumer.close(true);
                    Log.e(TAG, "onClick: 侧滑按钮点击2");
                    ToastUtils.showShort("导出");
                    ShareUtils.shareFile(HomeActivity.this, new ExportUtils().getZipFile(project));
                });
            }
        };

        //为RecyclerView添加配置
        LinearLayoutManager llm = new LinearLayoutManager(this);
        homeItemRv.setLayoutManager(llm);
        homeItemRv.setAdapter(projectCommonAdapter);
        scrollToPosition();
    }


    /**
     * 长按删除项目对话框
     *
     * @param
     *//**/
    private void showNormalDialog(Project project) {
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(HomeActivity.this);
        normalDialog.setTitle("删除项目");
        normalDialog.setMessage("是否确认删除项目'" + project.getName() + "'?");
        normalDialog.setPositiveButton("确定",
                (dialog, which) -> {
                    getPresenter().deleteProject(project);
                    projectList.remove(project);
                    projectCommonAdapter.notifyDataSetChanged();
                });
        normalDialog.setNegativeButton("关闭",
                (dialog, which) -> dialog.dismiss());
        //显示
        normalDialog.show();
    }

    private void initView() {
        bootomTabWidget = findViewById(R.id.home_view);
        bootomTabWidget.init(getSupportFragmentManager());
        //强制打开GPS
        openGPS(this);
 /*

        SmartSwipeRefresh.SmartSwipeRefreshDataLoader dataLoader = new SmartSwipeRefresh.SmartSwipeRefreshDataLoader() {
            @Override
            public void onRefresh(final SmartSwipeRefresh ssr) {
                long time = System.currentTimeMillis();
                getPresenter().getProjectList(FIRST_PAGE);
                homeItemRv.postDelayed(() -> ssr.finished(true), System.currentTimeMillis() - time);
            }

            @Override
            public void onLoadMore(final SmartSwipeRefresh ssr) {
                long time = System.currentTimeMillis();
                homeItemRv.postDelayed(() -> {
                    page++;
                    getPresenter().getProjectList(page);
                    ssr.finished(true);
                }, System.currentTimeMillis() - time);
            }
        };
        SmartSwipeRefresh.behindMode(homeItemRv, false, true).setDataLoader(dataLoader);
        //监听RecyclerView滚动状态
        homeItemRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (recyclerView.getLayoutManager() != null) {
                    getPositionAndOffset();
                }
            }
        });*/

    }

    /**
     * 记录RecyclerView当前位置
     */
    private void getPositionAndOffset() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) homeItemRv.getLayoutManager();
        //获取可视的第一个view
        View topView = layoutManager.getChildAt(0);
        if (topView != null) {
            //获取与该view的顶部的偏移量
            lastOffset = topView.getTop();
            //得到该View的数组位置
            lastPosition = layoutManager.getPosition(topView);
        }
    }

    /**
     * 让RecyclerView滚动到指定位置
     */
    private void scrollToPosition() {
        if (homeItemRv.getLayoutManager() != null && lastPosition >= 0) {
            ((LinearLayoutManager) homeItemRv.getLayoutManager()).scrollToPositionWithOffset(lastPosition, lastOffset);
        }
    }

    @Override
    public void getProjectList(List<Project> projectList, int page) {
        if (this.projectList.isEmpty() || page == FIRST_PAGE) {
            this.page = FIRST_PAGE;
            if (!this.projectList.isEmpty())
                this.projectList.clear();
            this.projectList.addAll(projectList);
            setAdapter();
            return;
        } else {
            this.projectList.addAll(projectList);
        }
        Log.e(TAG, "getProjectList: " + this.projectList.size());
        if (!firstEntry) {
            projectCommonAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        //initData();
    }



    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    /**
     * 权限获取失败
     *
     * @param requestCode /
     * @param perms       /
     */
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < perms.size(); i++) {
            stringBuilder.append(perms.get(i));
            stringBuilder.append("\n");
        }
        stringBuilder.replace(stringBuilder.length() - 2, stringBuilder.length(), "");
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            ToastUtils.showShort("已拒绝权限" + stringBuilder + "并不再询问");
            new AlertDialog.Builder(this)
                    .setMessage("此功能需要" + stringBuilder + "权限，否则无法正常使用，是否打开设置")
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).setNegativeButton("否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    App.getInstances().exit(-1);
                }
            }).show();

        }
    }
    public static final void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void gotoFragment() {
        bootomTabWidget.goFragment();
    }
}
